package ntd.util.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.StaticLog;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import ntd.util.UtilCatch;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class ToolPoi {

    public static byte[] docToDocx(InputStream inputStream) {
        // 读取 .doc 文件
        Document document = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            document = new Document(inputStream);
            SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.DOCX);
            document.save(outputStream, saveOptions);
            return outputStream.toByteArray();
        } catch (Exception e) {
            StaticLog.error(e, "[POI][docToDocx][{}]失败...");
        } finally {
            Opt.ofNullable(document).ifPresent(doc -> UtilCatch.tryCatchNoRes(doc::cleanup));
            Opt.ofNullable(outputStream).ifPresent(IoUtil::close);
            Opt.ofNullable(inputStream).ifPresent(IoUtil::close);
        }
        return null;
    }

    public static byte[] xlsToXlsx(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 创建新的 XLSX 文件
        XSSFWorkbook newWorkbook = new XSSFWorkbook();
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);


            // 将 XLS 文件中的每个工作表复制到新的 XLSX 文件中
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                HSSFSheet hssfSheet = workbook.getSheetAt(i);
                XSSFSheet xssfSheet = newWorkbook.createSheet(workbook.getSheetName(i));
                newWorkbook.getSheetAt(i).setSelected(true);
                newWorkbook.setSheetOrder(workbook.getSheetName(i), i);

                convertSheet(newWorkbook, hssfSheet, xssfSheet);
            }

            // 将 XLS 文件保存为 XLSX 格式
            newWorkbook.write(outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            StaticLog.error(e, "[POI][xlsToXlsx][{}]失败...");
        } finally {
            Opt.ofNullable(outputStream).ifPresent(IoUtil::close);
            Opt.ofNullable(inputStream).ifPresent(IoUtil::close);
            UtilCatch.tryCatchNoRes(() -> {
                newWorkbook.close();
            });
        }
        return null;
    }

    private static void convertSheet(XSSFWorkbook newWorkbook, HSSFSheet hssfSheet, XSSFSheet xssfSheet) {
        for (int row = 0; row <= hssfSheet.getLastRowNum(); row++) {
            org.apache.poi.hssf.usermodel.HSSFRow hssfRow = hssfSheet.getRow(row);
            if (hssfRow == null) {
                continue;
            }
            org.apache.poi.xssf.usermodel.XSSFRow xssfRow = xssfSheet.createRow(row);
            convertRow(newWorkbook, hssfRow, xssfRow);
        }
    }

    private static void convertRow(XSSFWorkbook newWorkbook, HSSFRow hssfRow, XSSFRow xssfRow) {
        XSSFCellStyle rowStyle = newWorkbook.createCellStyle();
        convertCellStyle(hssfRow.getRowStyle(), rowStyle);
        xssfRow.setRowStyle(rowStyle);
        for (int col = 0; col < hssfRow.getLastCellNum(); col++) {
            org.apache.poi.hssf.usermodel.HSSFCell hssfCell = hssfRow.getCell(col);
            if (hssfCell == null) {
                continue;
            }
            org.apache.poi.xssf.usermodel.XSSFCell xssfCell = xssfRow.createCell(col);
            XSSFCellStyle cellStyle = xssfCell.getCellStyle();

            if (hssfCell.getCellType() == CellType.STRING) {
                xssfCell.setCellValue(hssfCell.getStringCellValue());
            } else if (hssfCell.getCellType() == CellType.FORMULA) {
                xssfCell.setCellValue(hssfCell.getCellFormula());
            } else if (hssfCell.getCellType() == CellType.NUMERIC) {
                if (DateUtil.isCellInternalDateFormatted(hssfCell)) {
                    xssfCell.setCellValue(cn.hutool.core.date.DateUtil.formatDateTime(hssfCell.getDateCellValue()));

//                    CreationHelper createHelper = newWorkbook.getCreationHelper();
//                    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));
//                    xssfCell.setCellValue(hssfCell.getDateCellValue());
//                    xssfCell.setCellStyle(cellStyle);
                } else {
                    xssfCell.setCellValue(hssfCell.getNumericCellValue());
                }
            } else if (hssfCell.getCellType() == CellType.BOOLEAN) {
                xssfCell.setCellValue(hssfCell.getBooleanCellValue());
            }
            convertCellStyle(hssfCell.getCellStyle(), cellStyle);
        }
    }

    public static void convertCellStyle(HSSFCellStyle hssfCellStyle, XSSFCellStyle cellStyle) {
        if (ObjectUtil.isNull(hssfCellStyle)) {
            return;
        }
        // 使用 HSSFCellStyle 对象创建新的 CellStyle 对象
        cellStyle.setAlignment(hssfCellStyle.getAlignment());
        cellStyle.setBorderBottom(hssfCellStyle.getBorderBottom());
        cellStyle.setBorderLeft(hssfCellStyle.getBorderLeft());
        cellStyle.setBorderRight(hssfCellStyle.getBorderRight());
        cellStyle.setBorderTop(hssfCellStyle.getBorderTop());
//        cellStyle.setDataFormat(hssfCellStyle.getDataFormat());
        cellStyle.setFillBackgroundColor(hssfCellStyle.getFillBackgroundColor());
        cellStyle.setFillForegroundColor(hssfCellStyle.getFillForegroundColor());
        cellStyle.setFillPattern(hssfCellStyle.getFillPattern());
        cellStyle.setHidden(hssfCellStyle.getHidden());
        cellStyle.setIndention(hssfCellStyle.getIndention());
        cellStyle.setLocked(hssfCellStyle.getLocked());
        cellStyle.setRotation(hssfCellStyle.getRotation());
        cellStyle.setVerticalAlignment(hssfCellStyle.getVerticalAlignment());
        cellStyle.setWrapText(hssfCellStyle.getWrapText());
    }
}
